package com.zxg.zbc.biz.manager.impl;

import java.io.Serializable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.zxg.zbc.biz.manager.CacheManager;
import com.zxg.zbc.biz.manager.CacheService;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

public class DefaultCacheManager implements CacheManager {

	final static Logger log = LoggerFactory.getLogger(DefaultCacheManager.class);

	/**
	 * 环境 如果是jae 则用jae的内置缓存
	 */
	private String environment = "aliyun";

	private CacheService cacheService = null;

	@Autowired
	Cache baseCache;

	public String getEnvironment() {
		return environment;
	}

	public void setEnvironment(String environment) {
		this.environment = environment;
	}

	/*
	 * public CacheService getCacheService() { return cacheService; }
	 * 
	 * public void setCacheService(CacheService cacheService) {
	 * this.cacheService = cacheService; }
	 */

	public void init() {
		if (environment.equals("local")) {
			cacheService = new LocalCacheService(baseCache);

			log.warn("init local cache ");
		} else {
			// cacheService = CacheServiceFactory.getCacheService();
			log.warn("init aliyun cache ");
		}

	}

	@Override
	public boolean delete(String key) {
		// TODO Auto-generated method stub
		return cacheService.delete(key);
	}

	@Override
	public Serializable get(String key) {
		// TODO Auto-generated method stub
		return cacheService.get(key);
	}

	@Override
	public boolean put(String key, Serializable value) {
		if (value != null)
			return cacheService.put(key, value);
		return false;
	}

	@Override
	public boolean put(String key, Serializable value, int t) {
		if (value != null)
			return cacheService.put(key, value, t);
		return false;
	}
}

class LocalCacheService implements CacheService {

	Cache baseCache;

	public LocalCacheService() {
		// TODO Auto-generated constructor stub
	}

	public LocalCacheService(Cache baseCache) {
		super();
		this.baseCache = baseCache;
	}

	public Cache getBaseCache() {
		return baseCache;
	}

	public void setBaseCache(Cache baseCache) {
		this.baseCache = baseCache;
	}

	@Override
	public boolean delete(String key) {
		return baseCache.remove(key);
	}

	@SuppressWarnings("deprecation")
	@Override
	public Serializable get(String key) {
		Element ele = baseCache.getQuiet(key);
		if (ele == null || ele.isExpired())
			return null;
		return ele.getValue();
	}

	@Override
	public boolean put(String key, Serializable value) {
		// TODO Auto-generated method stub
		baseCache.put(new Element(key, value));
		return true;
	}

	@Override
	public boolean put(String key, Serializable value, int arg2) {
		Element ele = new Element(key, value);
		ele.setTimeToIdle(arg2);
		ele.setTimeToLive(arg2);
		baseCache.put(ele);
		return true;
	}

}
